package fudan.secret.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.*;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.apache.struts2.json.annotations.JSON;

import fudan.secret.util.HibernateSessionFactory;
import fudan.secret.domain.User;

public class LoginAction extends ActionSupport{
  private String uname;
  private String upassword;
  private Map<String,String> map;
 
  @JSON(serialize=false)
  public String getUname(){
	  return uname;
  }
  
  public void setUname(String name){
	  uname = name;
  }
  
  
  @JSON(serialize=false)
  public String getUpassword(){
	  return upassword;
  }
  
  public void setUpassword(String password){
	  upassword = password;
  }
  
  public Map<String, String> getResult() {  
      return map;  
   }  
  
  
  public String execute() throws Exception{
	  User user = new User();
	  Session session = HibernateSessionFactory.getSession();
	  Transaction tx = null;
	  map = new HashMap<String,String>();
	  try{
		  Criteria crit = session.createCriteria(User.class);
		  crit.add(Restrictions.eq("uname", uname));
		  User users = (User)crit.uniqueResult();
		  if(users != null){
			if(users.getUpassword().equals(upassword)){
				map.put("login", "true");
				map.put("uid", String.valueOf(users.getUid()));
			}else{
				map.put("login", "false");
			}
		  } else {
			  map.put("login", "false");
		  }
	  } catch(Exception e) {
		  map.put("login", "error");
		  e.printStackTrace();
		  tx.rollback();
	  } finally {
		  session.close();
	  }
	  return SUCCESS;
  }
}
